package cn.paidaxin.service.impl;

import cn.paidaxin.domain.dto.ClockInDTO;
import cn.paidaxin.domain.properties.AliyunParamProperties;
import cn.paidaxin.domain.properties.XinnuoMsgProperties;
import cn.paidaxin.service.ClockinCoreOpService;
import cn.paidaxin.utils.AliSmsUtils;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.DateUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Pai dx
 * @version 1.0.0
 * @date 2021-11-25 14:20
 **/
@Slf4j
@Service
public class ClockinCoreOpServiceImpl implements ClockinCoreOpService {

    @Autowired
    private AliyunParamProperties aliyunMsg;

    @Autowired
    private XinnuoMsgProperties xinnuoMsg;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean clockinCoreOp(ClockInDTO msgInfo) throws Exception {
        String phone = "";
        String message = "";
        String path = Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("")).getPath() + "lib/chromedriver.exe";
        System.setProperty("webdriver.chrome.driver", ResourceUtils.getFile(path).getPath());

        WebDriver driver = new ChromeDriver();
        driver.get(xinnuoMsg.getLoginUrl());
        //打卡
        WebElement userName = driver.findElement(By.id("UserName"));
        WebElement passWord = driver.findElement(By.id("PassWord"));
        userName.sendKeys(msgInfo.getUsername());
        passWord.sendKeys(msgInfo.getPassword());

        //签到信息
        String clockMsg = "";
        WebElement login = null;
        try {
            passWord.submit();
            login = driver.findElement(By.className("login"));

            //获取到登录名
            WebElement b = login.findElement(By.tagName("b"));
            WebElement a = b.findElement(By.tagName("a"));
            String name = a.getText();

            //打卡属性值
            WebElement main = driver.findElement(By.className("main"));
            WebElement img = main.findElement(By.tagName("img"));
            //签到成功
            String alt = img.getAttribute("alt");
            //签到时间
            String clockTime = main.findElement(By.tagName("span")).getText();


            if ("sb".equals(msgInfo.getClockType())) {
                clockMsg = name + " : " + alt + " " + clockTime;
            } else if ("xb".equals(msgInfo.getClockType())) {
                String xbTime = "";

                try {
                    xbTime = "下班打卡成功，打卡时间：" + DateUtils.formatDate(new Date());
                    driver.findElement(By.className("btn")).click();
                } catch (Exception e) {
                    e.printStackTrace();
                    xbTime = "下班打卡失败！";
                }
                clockMsg = name + " : " + alt + " " + xbTime;
            }
            Thread.sleep(6000L);

            redisTemplate.opsForValue().set("XINNUO:CLOCKIN:USERNAME:" + msgInfo.getClockType() + ":" + msgInfo.getUsername(), clockMsg, 600, TimeUnit.SECONDS);

            log.info("打卡信息:{}", clockMsg);
            log.info("打卡消息保存成功 - end ， 打卡类别：{}", msgInfo.getClockType());

            if (StringUtils.isEmpty(msgInfo.getPhone())) {
                phone = xinnuoMsg.getSmsSendPhone();
            } else {
                phone = msgInfo.getPhone();
            }
            message = "success";
        } catch (Exception e) {
            e.printStackTrace();
            log.info("账号密码错误");
            message = "passwordError";
            redisTemplate.opsForValue().set("XINNUO:CLOCKIN:USERNAME:" + msgInfo.getClockType() + ":" + msgInfo.getUsername(), "账号密码错误", 600);
        } finally {
            driver.quit();
        }
        //短信推送
        try {
            SendSmsResponse sendSmsResponse = AliSmsUtils.smsPush(phone, message, aliyunMsg.getAccessKeyId(), aliyunMsg.getAccessKeySecret());
            SendSmsResponseBody body = sendSmsResponse.getBody();
            System.out.println(body.getCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
